package com.ncdnapp.core.tracer;

import org.slf4j.MDC;

public class TraceContext {
    private static final String traceIdKey = "X-TraceId";
    private static final String spanIdKey = "X-SpanId";
    private static ThreadLocal<Tracer> threadLocalTracer = new InheritableThreadLocal<>();

    public static void start() {
        Tracer tracer = threadLocalTracer.get();
        if (tracer != null){
            MDC.put(traceIdKey,tracer.getTraceId());
            MDC.put(spanIdKey,tracer.getSpanId());
        }else{
            tracer = new Tracer(null);
            MDC.put(traceIdKey,tracer.getTraceId());
            MDC.put(spanIdKey,tracer.getSpanId());
            threadLocalTracer.set(tracer);
        }
    }

    public static void start(Tracer tracer){
        Tracer childTracer = new Tracer(tracer);
        MDC.put(traceIdKey,childTracer.getTraceId());
        MDC.put(spanIdKey,childTracer.getSpanId());
        threadLocalTracer.set(childTracer);
    }

    public static Tracer get() {
        return threadLocalTracer.get();
    }
    public static void clear() {
        threadLocalTracer.remove();
    }
    public static void end() {
        threadLocalTracer.remove();
    }
}
